package cn.sdhuijin.mediaplatform.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.util.Log;

/**
 * @author sunp@sdhuijin.cn:
 * @version 创建时间：2015年3月26日 下午5:01:18 类说明
 */
public class TxtUtil {

	public static String readTxtFile(String filePath) {
		String result = "";
		StringBuffer sb = new StringBuffer();
		try {
			String encoding = "GBK";
			File file = new File(filePath);
			if (file.isFile() && file.exists()) { // 判断文件是否存在
				InputStreamReader read = new InputStreamReader(
						new FileInputStream(file), encoding);// 考虑到编码格式
				BufferedReader bufferedReader = new BufferedReader(read);
				String lineTxt = null;
				while ((lineTxt = bufferedReader.readLine()) != null) {
					sb.append(getStringNoBlank(lineTxt));
				}
				if (sb != null) {
					result = sb.toString();
				}
				read.close();
			} else {
				Log.e("TXT读取", "找不到指定的文件");
			}
		} catch (Exception e) {
			e.printStackTrace();
			Log.e("TXT读取", "读取txt文件出现异常");
		}
		return result;
	}

	public static String getStringNoBlank(String str) {
		if (str != null && !"".equals(str)) {
			Pattern p = Pattern.compile("\\s{1}|\t|\r|\n");
			Matcher m = p.matcher(str);
			String strNoBlank = m.replaceAll("&nbsp;");
			return strNoBlank;
		} else {
			return str;
		}
	}
}
